package com.party.controller.sys.sysManage;

import com.party.common.MD5;
import com.party.common.Page;
import com.party.common.Tools;
import com.party.model.PartyLog;
import com.party.model.SysRole;
import com.party.model.SysUser;
import com.party.parBean.UserMsg;
import com.party.service.partylog.PartyLogService;
import com.party.service.sys.RoleService;
import com.party.service.sys.SysUserService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 系统用户
 * Created by IntelliJ IDEA.
 * User: Administrator
 * Date: 13-3-31
 * Time: 下午3:18
 * To change this template use File | Settings | File Templates.
 */
@Controller
@RequestMapping(value = "/sys/sysUser")
public class SysUserController {
    @Resource
    SysUserService sysUserService;
    @Resource
    RoleService roleService;
    @Resource
    PartyLogService partyLogService;

    private int pageSize = 9;

    /**
     * 用户列表
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public ModelAndView index(
            HttpServletRequest request,
            HttpServletResponse response
    ) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("/sys/sysmange/sys_admin_user");
        return modelAndView;
    }

    @RequestMapping(value = "/query")
    @ResponseBody
    public Map<String,Object> query(HttpServletRequest req) {
        Map<String, Object> map = new HashMap<String, Object>();
        String pageIndexStr = req.getParameter("pageIndex");
        String passport = req.getParameter("passport");
        String realname = req.getParameter("realname");
        String regtime = req.getParameter("regtime");

        int pageIndex = 1;
        if (pageIndexStr != null && !"".equals(pageIndexStr)) {
            pageIndex = Integer.parseInt(pageIndexStr);
        }

        SysUser sysUser = new SysUser();
        sysUser.setPassport(passport);
        sysUser.setRealname(realname);
        sysUser.setRegtime(regtime);
        Page p = this.sysUserService.getUserList(sysUser, pageSize, pageIndex);

        map.put("pageCount",p.getTotalPageCount() );
        map.put("tableData",p.getResult());
        return map;
    }

    @RequestMapping(value = "/add", method = RequestMethod.GET)
    public ModelAndView add(
            @RequestParam(value = "msg", required = false) String msg,
            HttpSession session,
            HttpServletRequest request,
            HttpServletResponse response
    ) {
        ModelAndView modelAndView = new ModelAndView();
        List<SysRole> roles = roleService.getRoles();
        modelAndView.addObject("roles", roles);
        modelAndView.setViewName("sys/sysmange/sys_admin_user_add");
        return modelAndView;
    }

    @RequestMapping(value = "/addData", method = RequestMethod.POST)
    public ModelAndView addData(
            @ModelAttribute("sysUser") SysUser sysUser,
            HttpSession session,
            HttpServletRequest request,
            HttpServletResponse response
    ) {
        ModelAndView modelAndView = new ModelAndView();
        String msg = "";
        sysUser.setPwd(MD5.encodeMD5(sysUser.getPwd()));
        int result = sysUserService.add(sysUser);
        if (result == 1) {
            msg = "恭喜，添加成功！";
        } else if (result == -2) {
            msg = "用户已经存在！";
        } else {
            msg = "添加失败！";
        }
        modelAndView.addObject("msg", msg);
        modelAndView.setViewName("redirect:/sys/sysUser/index.do");
        return modelAndView;
    }


    @RequestMapping(value = "/edit", method = RequestMethod.GET)
    public ModelAndView edit(
            @RequestParam("id") Integer id,
            HttpSession session,
            HttpServletRequest request,
            HttpServletResponse response
    ) {
        ModelAndView modelAndView = new ModelAndView();
        SysUser user = null;
        if(id != null && id > 0)
        {
            user = sysUserService.getUser(id);
        }
        List<SysRole> roles = roleService.getRoles();
        modelAndView.addObject("roles", roles);
        modelAndView.addObject("user", user);
        modelAndView.setViewName("sys/sysmange/sys_admin_user_edit");
        return modelAndView;
    }

    @RequestMapping(value = "/updateData", method = RequestMethod.POST)
    public ModelAndView updateData(
            @ModelAttribute("sysUser") SysUser sysUser,
            HttpSession session,
            HttpServletRequest request,
            HttpServletResponse response
    ) {
        ModelAndView modelAndView = new ModelAndView();
        String msg = "";
        sysUser.setPwd(MD5.encodeMD5(sysUser.getPwd()));
        int result = sysUserService.update(sysUser);
        if (result == 1) {
            msg = "修改成功！";
        }
        else {
            msg = "修改失败！";
        }
        modelAndView.addObject("msg", msg);
        modelAndView.setViewName("redirect:/sys/sysUser/index.do");
        return modelAndView;
    }

    /**
     * 删除用户
     *
     * @param ids
     * @return
     */
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> del(
            @RequestParam("ids") String ids
    ) {
        int num = 0;
        try {
            num = sysUserService.del(ids);
        } catch (Exception e) {
            num = -1;
            e.printStackTrace();
        }
        Map<String, Object> modelMap = new HashMap<String, Object>();
        modelMap.put("num", num);
        return modelMap;
    }

    @RequestMapping(value = "/showPwd")
    public ModelAndView edit(
            HttpSession session,
            HttpServletRequest request,
            HttpServletResponse response
    ) {
        int uid =0;
        if ((SysUser) session.getAttribute("sysUser") != null) {
            uid = ((SysUser) session.getAttribute("sysUser")).getUid();
        }

        ModelAndView modelAndView = new ModelAndView();
        SysUser user = null;
        if(uid > 0)
        {
            user = sysUserService.getUser(uid);
        }
        modelAndView.addObject("user", user);
        modelAndView.setViewName("/sys/sysmange/update_pwd");
        return modelAndView;
    }

    /**
     * 密码更改
     * @param session
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/changePwd")
    public ModelAndView changePwd(
            @RequestParam(value = "uid", required = false) Integer uid,
            @RequestParam(value = "nowPwd", required = false, defaultValue = "") String nowPwd,
            @RequestParam(value = "newPwd", required = false, defaultValue = "") String newPwd,
            HttpSession session,
            HttpServletRequest request,
            HttpServletResponse response
    ) {
        ModelAndView modelAndView = new ModelAndView();
        SysUser sysUser1=null;
        if ((SysUser) session.getAttribute("sysUser") != null) {
            sysUser1= ((SysUser) session.getAttribute("sysUser"));
            uid = sysUser1.getUid();
        }
        SysUser sysUser=new SysUser();
        sysUser.setUid(uid);
        sysUser.setPwd(newPwd);
        String msg = "";
        if (!"".equals(nowPwd)) {
            SysUser user = sysUserService.getUser(uid);
            nowPwd= MD5.encodeMD5(nowPwd);
            if(user.getPwd().equals(nowPwd)){
                newPwd=MD5.encodeMD5(newPwd);
                user.setPwd(newPwd);
                int num= sysUserService.changePwd(user);
                if (num == 1) {
                    msg = "设置成功！";
                } else {
                    msg = "设置失败！";
                }
            }else {
                msg = "原始密码不对，请重新输入！";
            }
        }else{
            msg = "设置失败！";
        }
        modelAndView.addObject("msg", msg);
        modelAndView.addObject("user", sysUser1);
        modelAndView.setViewName("/sys/sysmange/update_pwd");
        return modelAndView;
    }


    /**
     * 党员流程
     */
    @RequestMapping(value = "/flow")
    public ModelAndView flow(
            @RequestParam(value = "id")Integer id,
            HttpServletRequest request,
            HttpServletResponse response
    ) {
        ModelAndView modelAndView = new ModelAndView();
        SysUser user=sysUserService.getUser(id);
        modelAndView.addObject("user",user);
        modelAndView.setViewName("/sys/sysmange/sys_user_flow");

        return modelAndView;
    }

    @RequestMapping(value = "/changeOneTwoThree")
    @ResponseBody
    public Map<String,Object> changeOneTwoThree(HttpServletRequest req) {
        Map<String, Object> map = new HashMap<String, Object>();
        int status = 0;
        String value = req.getParameter("value");
        String uid = req.getParameter("uid");
        String partyEndTime = req.getParameter("partyEndTime");
        Date endDate = new Date();
        if(partyEndTime != null && !"".equals(partyEndTime))
        {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            try {
                endDate = sdf.parse(partyEndTime);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }

        String [] sts = {"1","1","1"};
        if(value != null && !"".equals(value) && uid != null && !"".equals(uid) && Tools.isNumber(uid))
        {
            SysUser user = this.sysUserService.getUser(Integer.parseInt(uid));
            if(user != null)
            {
                sts = value.split(",");
                user.setLone(sts[0]);
                user.setLtwo(sts[1]);
                user.setLthree(sts[2]);
                user.setPartystarttime(new Date());//开始时间就是当前时间
                user.setPartyendtime(endDate);//开始时间就是当前时间
                this.sysUserService.update(user);

                /**
                 * 记录党员流程
                 */
                PartyLog partyLog=new PartyLog();
                partyLog.setAuthor(user.getRealname());
                partyLog.setTime(new Date());
                partyLog.setPartystarttime(new Date());
                partyLog.setPartyendtime(endDate);
                partyLog.setPartystage(sts[0]+"\t"+sts[1]+"\t"+sts[2]);
                partyLogService.addPartyLog(partyLog);
                status = 1;
            }
        }

        map.put("status",status );
        map.put("one",sts[0]);
        map.put("two",sts[1]);
        map.put("three",sts[2]);
        return map;
    }

    /**
     * 党员流程数据
     */
    @RequestMapping(value = "/flowData")
    public ModelAndView flowData(
            @RequestParam(value = "uid")Integer uid,
            @RequestParam(value = "node")String node,
            HttpServletRequest request,
            HttpServletResponse response
    ) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("uid",uid);
        modelAndView.setViewName("/sys/sysmange/sys_user_flow");

        return modelAndView;
    }
}
